layui.use([
	'element',
	'jquery',
	'laytpl',
	'exutil',
	'exconfig',
	'exrouter',
	'sysUser',
	'sysMenu'
], function() {

	var element = layui.element,
		$ = layui.$,
		laytpl = layui.laytpl,
		exutil = layui.exutil,
		exconfig = layui.exconfig,
		exrouter = layui.exrouter,
		sysUser = layui.sysUser,
		sysMenu = layui.sysMenu;

	var els = {
		elmIndexContent: $('#index_content'),
		elmAdminName: $('#admin_name'),
		elmTopMenu: $('#top_menu'),
		elmLeftMenu: $('#left_menu'),
		elmLogoutBtn: $('#logout'),
		elmRefreshBtn: $('#refresh'),
		elmDocument: $(document),
		elmMain: $('#main'),
		elmFoot: $('#foot'),
		elmGoLeft: $('.wt-go-left'),
		elmGoRight: $('.wt-go-right'),
		tplStairMenu: $('#stair_menu'),
		tplSecondaryMenu: $('#secondary_menu'),
		tplMainContent: $('#main_content')
	};

	var datas = {
		menu: null,
		tabCurrentX: 0
		// domain: cmhttp.getUrlParam('domain')
	};

	var methods = {
		init: function() {
			var account = exutil.getCookie('showAccount');
			if (account) {
				els.elmAdminName.text(account);
			}
			this._initMenu();
		},
		_initMenu: function() {
			var that = this;
			var topMenu = els.tplStairMenu.html();
			var leftMenu = els.tplSecondaryMenu.html();
			
			sysMenu.getTreeForCurrentUser()
				.done(function(resp) {
					var menuData = that._formatMenuData(resp);
					// console.log(menuData);
					laytpl(topMenu).render(menuData, function(html) {
						els.elmTopMenu.html(html);
						element.render("nav", "top_menu");
					});
					
					laytpl(leftMenu).render(menuData, function(html) {
						els.elmLeftMenu.append(html);
						element.render("nav", "left_menu");
					});
					
					exconfig.currentShowTopMenuKey = menuData[0].menuKey;
					exconfig.currentShowMenuKey[0] = menuData[0].menuKey;
					if(menuData[0].children && menuData[0].children.length > 0){
						exconfig.currentShowMenuKey[1] = menuData[0].children[0].menuKey;
						if(menuData[0].children[0].children && menuData[0].children[0].children.length > 0){
							exconfig.currentShowMenuKey[2] = menuData[0].children[0].children[0].menuKey;
						}
					}
					
					that._initTab(menuData);
					
				})
		},
		_formatMenuData: function(menus, parentArr){
			if($.isArray(menus) && menus.length > 0){
				var len = menus.length;
				for(var i=0; i<len; i++){
					menus[i].linkKey = [];
					if(menus[i].parentKey === "0"){
						menus[i].linkKey.push(menus[i].menuKey);
					}else{
						var flag = parentArr.join()+","+menus[i].menuKey;
						menus[i].linkKey = flag.split(",");
					}
					menus[i].children = this._formatMenuData(menus[i].children, menus[i].linkKey)
				}
				return menus;
			}else{
				return null;
			}
		},
		_initTab: function(menuData){
			var len = exconfig.currentShowMenuKey.length;
			
			if(len === 0){
				return;
			}else if(len === 1){
				var menu = menuData[0];
			}else if(len === 2){
				var menu = menuData[0].children[0];
			}else if(len === 3){
				var menu = menuData[0].children[0].children[0];
			}else if(len === 4){
				var menu = menuData[0].children[0].children[0].children[0];
			}
				
			this.openWin({
				url: menu.webUri,
				id: menu.id,
				key: menu.linkKey.join(),
				title: menu.name
			}, true);
		},
		// 打开iframe
		openWin: function(obj, isFirst) {
			var mainContent = els.tplMainContent.html(),
				data = {
					url: obj.url,
					id: obj.id,
					key: obj.key
				},
				that = this,
				title = obj.title,
				allWidth = $('.layui-tab-title').get(0).scrollWidth,
				showWidth = $('.layui-tab-title').width();
 
			if (!isFirst) {
				title += '<a href="javascript:void(0);" data-id="' + obj.id + '" data-key="'+ obj.key +'"/></a>';
			}
			
			// 更新menuKey
			exconfig.currentShowMenuKey = obj.key.split(",");

			if ($('li[lay-id="' + obj.key + '"]').length > 0) {
				
				var lx = $('li[lay-id="' + obj.key + '"]').position().left,
					firstX = Math.abs($('li[lay-id]').first().position().left),
					wd = $('li[lay-id="' + obj.key + '"]').width(),
					absLX = Math.abs(lx),
					showWidth = $('.layui-tab-title').width();
					
				if(lx<0){
					$('.layui-tab-title').scrollLeft(firstX-absLX);
				}else if(lx>0){
					var standardDistance = showWidth-wd;
					if(lx>standardDistance){
						$('.layui-tab-title').scrollLeft(firstX+lx-standardDistance+30);
					}
				}
				
				element.tabChange('main', obj.key);
			} else {
				laytpl(mainContent).render(data, function(html) {
					
					// 限制数量
					if (exconfig.tabCount && els.elmMain.find("li").length >= exconfig.tabCount) {
						var tabKey = els.elmMain.find("li:eq(1)").attr("lay-id");
						var index = exconfig.tabs.indexOf(tabKey);
						exconfig.tabs.splice(index,1);
						element.tabDelete('main', tabKey);
					}

					element.tabAdd('main', {
						title: title,
						content: html,
						id: obj.key
					});
					
					// that._initTabBtn();

					var oLoading = $('#' + obj.id);
					var oIframe = $('iframe[data-id="' + obj.id + '"]')[0];

					if (oIframe.attachEvent) {
						oIframe.attachEvent("onload", function() {
							//iframe加载完成后你需要进行的操作  
							oLoading.hide();
						});
					} else {
						oIframe.onload = function() {
							//iframe加载完成后你需要进行的操作  
							oLoading.hide();
						};
					}

					element.tabChange('main', obj.key);
					exconfig.tabs.push(obj.key);
				});
			} 
		},
		_initTabBtn: function(){
			var allWidth = $('.layui-tab-title').get(0).scrollWidth,
				showWidth = $('.layui-tab-title').width();
				
			if(allWidth && showWidth){
				if(allWidth > showWidth){
					els.elmGoRight.removeClass("layui-btn-disabled");
				}
				$('.layui-tab-title').scrollLeft(allWidth - showWidth);
			}
		}

	};

	methods.init();

	/**
	 * 事件处理
	 */
	
	
	// 登出
	els.elmLogoutBtn.click(function(ev) {
		sysUser.logout()
			.then(function(resp) {
				exutil.delCookie('showAccount');
				exutil.delCookie('loginusertoken');
				exutil.delCookie('userId');
				exutil.delCookie('orgId');
				exutil.replace(exrouter.base.login());
			});
		ev.stopPropagation();
	});

	// 更新
	els.elmRefreshBtn.click(function(ev) {
		var oLoading = $('#main>.layui-tab-content>.layui-show>div').show();
		var actionWin = $('#main>.layui-tab-content>.layui-show>iframe');
		actionWin.prop('src', exutil.addRendomForUrl(actionWin.prop('src')));
		ev.stopPropagation();
	});

	// 一级菜单
	els.elmTopMenu.on('click', 'li', function() {
		var id = String($(this).data('id')),
			url = $(this).data('url'),
			key = $(this).data('key'),
			title = $(this).find('a').html(),
			len = exconfig.currentShowMenuKey.length,
			beforeTopMenuKey = exconfig.currentShowTopMenuKey,
			beforeMenuKey = exconfig.currentShowMenuKey;
			
			
		// 防止重复点击
		if (key === beforeTopMenuKey) {
			return;
		}
		
		// 切换
		var beforeLeftMenu = $('ul[data-pkey="' + beforeTopMenuKey + '"]').addClass('layui-hide');
		var currentLeftMenu = $('ul[data-pkey="' + key + '"]').removeClass('layui-hide');
		
		if (key === beforeMenuKey[0]){
			if (len === 3) {
				currentLeftMenu.find('li[data-key="' + beforeMenuKey[0] + ',' + beforeMenuKey[1] +'"]').addClass('layui-nav-itemed');
			}
		}
		
		if (beforeMenuKey[0] === beforeTopMenuKey) {
			// 之前一级菜单有高亮项
			if (len === 2) {
				beforeLeftMenu.find('li').removeClass('layui-nav-itemed');
			}
			
			if (len === 3){
				beforeLeftMenu.find('li[data-key!="' + beforeMenuKey[0] + ',' + beforeMenuKey[1] +'"]').removeClass('layui-nav-itemed');
			}
		} else {
			// 之前一级菜单无高亮项
			beforeLeftMenu.find('li').removeClass('layui-nav-itemed');
		}
		
		exconfig.currentShowTopMenuKey = key;

		// 带页面跳转
		if (url) {
			if (len > 1) {
				var sli = $('ul[data-pid="' + beforeMenuKey[0] + '"]>li[data-id="' + beforeMenuKey[0] + '-' + beforeMenuKey[1] + '"]');
			}

			if (len === 2) {
				sli.removeClass('layui-this');
			}

			if (len === 3) {
				sli.removeClass('layui-nav-itemed');
				sli.find('dd[data-id="' + beforeMenuKey.join() + '"]').removeClass('layui-this');
			}

			methods.openWin({
				url: url,
				id: id,
				key: key,
				title: title
			});
		}
	});

	// 左侧菜单
	els.elmLeftMenu.on('click', '.menu-item', function() {
		var id = String($(this).data('id')),
			url = $(this).data('url'),
			key = $(this).data('key'),
			title = $(this).find('a').html(),
			len = exconfig.currentShowMenuKey.length,
			beforeTopMenuKey = exconfig.currentShowTopMenuKey,
			beforeMenuKey = exconfig.currentShowMenuKey,
			currentKey = key.split(",");
			
		// 防止重复点击
		if (key === beforeMenuKey.join()) {
			return;
		}

		if (url) {
			if (len > 1) {
				var sli = $('ul[data-pkey="' + beforeMenuKey[0] + '"]>li[data-key="' + beforeMenuKey[0] + ',' + beforeMenuKey[1] + '"]');
			}
			
			if (len === 2) {
				sli.removeClass('layui-this');
			}
			
			if (len === 3) {
				var beforeMenu = beforeMenuKey[0] + "," + beforeMenuKey[1];
				var currentMenu = currentKey[0] + "," + currentKey[1];
				if(beforeMenu !== currentMenu){
					sli.removeClass('layui-nav-itemed');
				}
				sli.find('dd[data-key="' + beforeMenuKey.join() + '"]').removeClass('layui-this');
			}
			
			methods.openWin({
				url: url,
				id: id,
				key: key,
				title: title
			});
		}

	});
	
	// 删除tab
	els.elmMain.on('click', 'a', function(ev) {
		var tabKey = $(this).data('key');
		var index = exconfig.tabs.indexOf(tabKey);
		exconfig.tabs.splice(index,1);
		element.tabDelete('main', tabKey);
	});

	// tab切换
	element.on('tab(main)', function(data) {
		var current_tabKey = $(this).attr('lay-id');
		if (current_tabKey === exconfig.currentShowMenuKey.join()) {
			return;
		}

		var current_smkey_infos = current_tabKey.split(','),
			before_smkey_infos = exconfig.currentShowMenuKey;
		
		if (current_smkey_infos[0] !== exconfig.currentShowTopMenuKey) {
			$('#top_menu>li[data-key="' + exconfig.currentShowTopMenuKey + '"]').removeClass('layui-this');
			$('#top_menu>li[data-key="' + current_smkey_infos[0] + '"]').addClass('layui-this');
			var beforeLeftMenu = $('ul[data-pkey="' + exconfig.currentShowTopMenuKey + '"]').addClass('layui-hide');
			var currentLeftMenu = $('ul[data-pkey="' + current_smkey_infos[0] + '"]').removeClass('layui-hide');
			exconfig.currentShowTopMenuKey = current_smkey_infos[0];
		}

		switch (before_smkey_infos.length) {
			case 2:
				$('ul[data-pkey="' + before_smkey_infos[0] + '"]>li[data-key="' + before_smkey_infos.join() + '"]').removeClass('layui-this');
				break;
			case 3:
				var oldId = before_smkey_infos[0] + ',' + before_smkey_infos[1];
				if(before_smkey_infos[1] !== current_smkey_infos[1]){
					$('ul[data-pkey="' + before_smkey_infos[0] + '"]>li[data-key="' + oldId + '"]').removeClass('layui-nav-itemed');
				}
				$('ul[data-pkey="' + before_smkey_infos[0] + '"] dd[data-key="' + before_smkey_infos.join() + '"]').removeClass('layui-this');
				break;
		}

		switch (current_smkey_infos.length) {
			case 2:
				$('ul[data-pkey="' + current_smkey_infos[0] + '"]>li[data-key="' + current_tabKey + '"]').addClass('layui-this');
				break;
			case 3:
				var newId = current_smkey_infos[0] + ',' + current_smkey_infos[1];
				$('ul[data-pkey="' + current_smkey_infos[0] + '"]>li[data-key!="' + newId + '"]').removeClass('layui-nav-itemed');
				$('ul[data-pkey="' + current_smkey_infos[0] + '"]>li[data-key="' + newId + '"]').addClass('layui-nav-itemed');
				$('ul[data-pkey="' + current_smkey_infos[0] + '"] dd[data-key="' + current_tabKey + '"]').addClass('layui-this');
				break;
		}

		exconfig.currentShowMenuKey = current_smkey_infos;
	});

	// tab向左
	els.elmGoLeft.on('click', function(ev) {
		var allWidth = $('.layui-tab-title').get(0).scrollWidth,
			showWidth = $('.layui-tab-title').width(),
			diffWidth = allWidth - datas.tabCurrentX - showWidth;

		if (allWidth !== showWidth) {
			if (diffWidth < showWidth) {
				datas.tabCurrentX = allWidth - showWidth;
			} else {
				datas.tabCurrentX += showWidth;
			}
			$('.layui-tab-title').scrollLeft(datas.tabCurrentX);
			
		}
		ev.stopPropagation();
	});

	// tab向右
	els.elmGoRight.on('click', function(ev) {
		var allWidth = $('.layui-tab-title').get(0).scrollWidth,
			showWidth = $('.layui-tab-title').width();

		if (allWidth !== showWidth) {
			if (datas.tabCurrentX < showWidth) {
				datas.tabCurrentX = 0;
			} else {
				datas.tabCurrentX -= showWidth;
			}
			$('.layui-tab-title').scrollLeft(datas.tabCurrentX);
		}

		ev.stopPropagation();
	});

	// 修改密码
	els.elmDocument.on('click', '#reset_password', function(ev) {
		$(this).parent().removeClass('layui-this');
		cmwindow.open({
			title: "修改密码",
			type: 2,
			skin: 'wt-layer', //样式类名
			area: ['500px', '284px'],
			closeBtn: 1, //不显示关闭按钮
			content: cmrouter.path.reset()
		});
		ev.stopPropagation();
	});

	// 左侧菜单折叠
	els.elmDocument.on('click', ".lmenu", function(ev) {
		$(this).toggleClass("lmenu-hide").toggleClass("lmenu-show");
		if ($(this).hasClass("lmenu-hide")) {
			$('.layui-side').css('width', '0px');
			els.elmMain.css('left', '0px');
			els.elmFoot.css('left', '0px');
		} else {
			$('.layui-side').css('width', '200px');
			els.elmMain.css('left', '200px');
			els.elmFoot.css('left', '200px');
		}
		ev.stopPropagation();
	});
});
